package eip.chapter7.contentrouter.util;

import java.io.StringReader;
import java.io.StringWriter;

import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.JiBXException;

import eip.chapter7.contentrouter.HotelBooking;

public class JiBXHelper {

	private static IBindingFactory bookingFactory;
	
	private static IBindingFactory getBookingFactory() throws JiBXException {
		if(bookingFactory == null) {
			bookingFactory = BindingDirectory.getFactory(HotelBooking.class);
		}
		return bookingFactory;
	}
	
	public static String createBookinginXML(HotelBooking booking) throws JiBXException {
		StringWriter writer = new StringWriter();
		getBookingFactory().createMarshallingContext().marshalDocument(booking, "UTF-8", null, writer);
		return writer.toString();
	}
	
	public static HotelBooking createBookingFromXML(String bookingMessage) throws JiBXException {
		return (HotelBooking) getBookingFactory().createUnmarshallingContext().
				unmarshalDocument(new StringReader(bookingMessage), null);
	}
}
